<?php
namespace app\admin\controller\soft;
use app\providers\BaseController;
use app\providers\Request;
use app\admin\controller\soft\PageCreate;
use app\admin\model\SystemUser;
use hg\apidoc\annotation as Apidoc;


/**
* @Apidoc\Title("初始化系统")
* @Apidoc\Group("base")
* @Apidoc\Sort(1)
*/
class Install extends BaseController
{
    
    /**
    * 初始化系统
    * @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/auth/logout")
    * @Apidoc\Method("POST")
    * @Apidoc\Returned("退出成功")
    * @global login false
    */
    public function create(){
        
        if( file_exists( base_path().'/views/system/baseInstall/insall.lock' ) ){
           return \Api::ReError('不能二次初始化！');
        }
        
        $param = request()->post();
        
        try{
            //添加.env文件，配置数据库
            file_put_contents(base_path().'/.env',"
DB_CONNECTION=$param[type]
DB_HOST=$param[hostname]
DB_PORT=$param[hostport]
DB_DATABASE=$param[database]
DB_USERNAME=$param[username]
DB_PASSWORD=$param[password]
DB_PREFIX=$param[prefix]
        ");
            
            //初始化系统数据表
            $res = db_multi_query(file_get_contents(base_path().'database/sql/system.sql'));
            file_put_contents(base_path().'/views/system/baseInstall/insall.lock','已安装初始数据');
            
            //添加管理员
            (new SystemUser)->addUser([
                "user_name"=>'管理员',        
                "user_code"=>$param['admin'],      
                "user_pwd"=>$param['admin_pwd'],
                "is_admin"=>1,
                "org_id"=>1
            ]);

            //创建页面
            (new PageCreate)->create();
            
            return \Api::ReSucess('',"操作成功！");
            
        } catch (\Exception $e) {
            unlink(base_path().'/views/system/baseInstall/insall.lock');
            return \Api::ReError("链接错误：".$e->getMessage());    
        }
    }
	
    
    /** 
    * 初始化系统
    */
    public function xmlInstall(Request $request){
        return false;
    }
    
}
